package com.crawleService.shanxitobaccoWebsite.service.impl;

import com.crawleService.shanxitobaccoWebsite.service.SmokeInfoShanxiTobaccoCrawlerService;
import com.crawleService.util.shanxitobaccoUtil.SUtil;

import com.projectCommon.bean.Info;
import com.projectCommon.bean.ProductBeanResult;
import com.projectCommon.util.springUtil.annotation.MethodEventDescription;
import com.projectCommon.bean.httpSmokeBean.shanxitobaccobean.request.SmokeInfoBean;
import com.projectCommon.bean.httpSmokeBean.shanxitobaccobean.response.OrderingInformation;
import com.projectCommon.bean.httpSmokeBean.shanxitobaccobean.response.SmokeResult;
import com.projectCommon.util.commonUtil.CUtil;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2024/04/04/11:57
 * @target 心若有所向往，何惧道阻且长
 */
@Service
public class SmokeInfoShanxiTobaccoCrawlerServiceImpl implements SmokeInfoShanxiTobaccoCrawlerService {

    /**
     * @param page 当前页
     * @param rows 当前页数量
     * @return 得到烟的信息通过分页参数。
     */
    @Override
    public SmokeResult selectSmokeInfoByPage(Integer page, Integer rows) {
        SmokeResult smokeResult = sendSmokeInfoRequest(new OkHttpClient(), 1, 16);
        return smokeResult;
    }

    /**
     * 得到所有的烟的信息
     *
     * @return
     */
    @Override
    @MethodEventDescription(event = "查询所有网页在销信息", logLevel="debug")
    public SmokeResult selectAllSmokeInfo() {
        int startPage = 1;
        int rows = 16;
        OkHttpClient client = new OkHttpClient();
        SmokeResult smokeResult = sendSmokeInfoRequest(client, startPage, rows);
        List<ProductBeanResult> resultList = smokeResult.getRows();
        int result = (Integer.parseInt(smokeResult.getTotal()) + rows - 1) / rows; // 将x除以16并向上取整
        for (int i = 0; i < result - 1; i++) {
            SmokeResult res = sendSmokeInfoRequest(client, i + 2, rows);
            List<ProductBeanResult> row = res.getRows();
            resultList.addAll(row);
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return smokeResult;
    }

    /**
     * 查询订烟时的可用量
     * 是不是订烟的时候才能查到呢？？  所以的话在订烟之前查询这个接口，可能这个接口平常的时候是没有开放的！！！
     * 那么就等订烟的时候再查询
     *
     * @return
     */
    @Override
    public OrderingInformation selectAvailableAmount() {
        OkHttpClient client = new OkHttpClient();
        String url = "https://shanxitobacco.com/wdk?action=ecw.page&method=call_service&ajaxparamtime=" + System.currentTimeMillis();
        String wppm = SUtil.encipher(CUtil.obgToJson(new SmokeInfoBean().init6()));
        FormBody formBody = new FormBody.Builder()
                .add("wppm", wppm)
                .build();
        Request.Builder builder = new Request.Builder();
        builder = CUtil.setCookie(builder, Info.ShanxiTobaccoCookieMap);
        Request request = builder
                .url(url)
                .post(formBody)
                .build();
        OrderingInformation orderingInformation = null;
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            orderingInformation = CUtil.jsonToObj(string, OrderingInformation.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return orderingInformation;
    }

    /**
     * 下载对应的图片借口
     *
     * @param fileid
     */
    @Override
    public byte[] downHttpPic(String fileid) {
        OkHttpClient client = new OkHttpClient();
        String url = "https://sx.jinye.cn/wdk?action=ecw.file&method=attachment_download&fileid=" + fileid;
        Request.Builder builder = new Request.Builder();
        builder = CUtil.setCookie(builder, Info.ShanxiTobaccoCookieMap);
        Request request = builder
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("没有图片");
        return null;
    }

    /**
     * @param client http客户端
     * @param page   第几页
     * @param rows   几条数据
     * @return 返回信息集合
     */
    public SmokeResult sendSmokeInfoRequest(OkHttpClient client, Integer page, Integer rows) {
        String url = "https://sx.jinye.cn/wdk?action=ecw.page&method=call_service&ajaxparamtime=" + System.currentTimeMillis();
        String wppm = SUtil.encipher(CUtil.obgToJson(new SmokeInfoBean(page, rows).init1()));
        FormBody formBody = new FormBody.Builder()
                .add("wppm", wppm)
                .build();
        Request.Builder builder = new Request.Builder();
        builder = CUtil.setCookie(builder, Info.ShanxiTobaccoCookieMap);
        Request request = builder
                .url(url)
                .post(formBody)
                .build();
        SmokeResult smokeResult = null;
        try {
            Response response = client.newCall(request).execute();
            smokeResult = CUtil.jsonToObj(response.body().string(), SmokeResult.class);
            CUtil.set_SetCookie(response.headers(), Info.ShanxiTobaccoCookieMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return smokeResult;
    }
}